import { defineStore } from 'pinia'
import router from '@/router'
import { api } from '@/api/index'
const { RequestMenu, RequestReourceAuthor } = api
// 加载@/views目录下所有的.vue单文件组件
const viteComponent = import.meta.glob('@/views/**/*.vue')
// console.log('viteComponent ',viteComponent)
/**
 * 动态权限菜单
 *   1. 调用菜单接口获取菜单列表数据
 *   2. 使用elementPlus组件库实现左侧菜单栏
 *   3. 格式化数据显示到菜单栏
 */
export const useMenuStore = defineStore('menu', {
    state: () => {
        return {
            menuList: [],
            resourceList: [],
            device:true
        }
    },
    actions: {
        saveMenuList(roleId: number) {
            return new Promise(async (resolve, reject) => {
                let menuPromise = RequestMenu(roleId)
                let resourcePromise = RequestReourceAuthor(roleId)
                //多个promise封装的异常操作用上个方法实现 Promise.all([promise,promise]) Promise.race([promise,promise])
                const dataList: any = await Promise.all([
                    menuPromise,
                    resourcePromise,
                ])
                const menuData = dataList[0]
                const resourceData = dataList[1]
                if (menuData.resultCode === 1) {
                    // 1.保存网络菜单接口数据
                    this.menuList = menuData.resultInfo
                    // 2.格式化菜单数据
                    let routeMenuList = formateRouterMenu(menuData.resultInfo)
                    // 3.添加动态路由,router对象
                    routeMenuList.forEach((route: any) =>
                        router.addRoute(route)
                    )
                }
                if (resourceData.resultCode === 1) {
                    this.resourceList = resourceData.resultInfo.resource
                }

                resolve('')
            })
        },
        setDevice(device:boolean){
            this.device = device
        }
    },
    getters: {
        // 组件获取list值,直接store.list,不用写getters. 与vuex 中store.getters.list不同
        list: state => state.menuList,
        devicebool:state=>state.device
    },
    // 使用该插件，开启数据缓存
    persist: {
        //这里存储默认使用的是session
        enabled: true,
        strategies: [
            {
                //key的名称
                key: 'menuKey',
                //更改默认存储，我更改为localStorage
                storage: localStorage,
                // 可以选择哪些进入local存储，这样就不用全部都进去存储了
                // 默认是全部进去存储
                paths: ['menuList', 'resourceList','device'],
            },
        ],
    },
})

/**
 * 格式化动态菜单
 * {                       {
 *     label:'',               label:'',
 *     path:''       =>        path:'/main_shop'
 *                             component:  Home
 *     children:[]             children:[
 *                                  {
 *                                      path:'/banner/list'
 *                                      component:  import('plateform/banner/list.vue')
 *                                  }
 *                              ]
 *
 * }                       }
 */
const formateRouterMenu = (menuList: any) => {
    let routeMenuList: any = [] // 格式化之后路由列表
    menuList.forEach((item: any) => {
        let children
        if (item.children && Array.isArray(item.children)) {
            children = formateRouterMenu(item.children)
        }
        const { id, label, iconCls, path, meta } = item
        //构造新的路由项route
        let newRoute = { id, label, iconCls, path, meta, children }
        //新的路由项增加component组件映射
        // 一级菜单路由直接返回Home组件
        if (path.indexOf('/main') !== -1) {
            newRoute = {
                ...newRoute,
                component: () => import('@/views/Home.vue'),
            }
        } else {
            //二级菜单路由返回对应路径组件
            newRoute = {
                ...newRoute,
                component:
                    viteComponent[`/src/views/plateform${newRoute.path}.vue`],
            }
        }

        routeMenuList.push(newRoute)
    })
    return routeMenuList
}
